package com.example.demo.action;

import com.example.demo.process.ReplaceProcess;
import com.example.demo.strategy.stringStrategy.AddGetPrefixConverter;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.project.Project;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

/**
 * 添加 get 前缀的 Action
 * @author dxw
 */
public class AddGetPrefixAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        Editor editor = (Editor) event.getDataContext().getData("editor");
        Project project = event.getProject();

        if (editor != null) {
            SelectionModel selectionModel = editor.getSelectionModel();
            String selectedText = selectionModel.getSelectedText();
            
            // 如果没有选中文本，则自动选中光标所在的单词
            if (StringUtils.isBlank(selectedText)) {
                editor.getCaretModel().getCurrentCaret().selectWordAtCaret(true);
                selectedText = selectionModel.getSelectedText();
            }
            
            if (StringUtils.isNotBlank(selectedText)) {
                // 执行转换
                AddGetPrefixConverter converter = new AddGetPrefixConverter();
                String result = converter.execute(selectedText);
                // 替换文本
                ReplaceProcess.replaceText(result, editor, project);
            }
        }
    }

    @Override
    public void update(@NotNull AnActionEvent event) {
        // 始终显示菜单项，只要编辑器存在
        Editor editor = (Editor) event.getDataContext().getData("editor");
        event.getPresentation().setEnabledAndVisible(editor != null);
    }
}

